#include "stdafx.h"
#include "AutoHandle.h"


AutoHandle::AutoHandle()
{
}

AutoHandle::~AutoHandle()
{
}

void AutoHandle::EraseHandle( HANDLE handle )
{
	std::vector<HANDLE>::iterator it = find( m_autoHandles.begin(), m_autoHandles.end(), handle );
	if ( it != m_autoHandles.end() )
	{
		*it = INVALID_HANDLE_VALUE;

		//	Remove all handles from the end of the vector that have been erased
		HANDLE testHandle;
		while (m_autoHandles.size() > 0 && INVALID_HANDLE_VALUE == ( testHandle = m_autoHandles.back() ) )
		{
			m_autoHandles.pop_back();
		}
	}
}

HANDLE AutoHandle::GetAutoHandle( unsigned long number /*= 0*/ )
{
	if ( number >= m_autoHandles.size() )
	{
		return INVALID_HANDLE_VALUE;
	}

	return m_autoHandles[ number ];
}

size_t AutoHandle::GetSize()
{
	return m_autoHandles.size();
}

HANDLE AutoHandle::PopHandle()
{
	HANDLE handle = m_autoHandles[ m_autoHandles.size() - 1 ];
	m_autoHandles.pop_back();
	return handle;
}

long AutoHandle::PushHandle( HANDLE handle )
{
	long index = (long)m_autoHandles.size();
	m_autoHandles.push_back( handle );
	return index;
}
